package com.summer.user.service.impl;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.util.StringUtils;

public class MyUrlAuthenticationFailureHandler extends
		SimpleUrlAuthenticationFailureHandler {
	private boolean useModalBox;

	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {
		String targetUrl = request.getHeader("Referer");
		String failTargetUrl = request
				.getParameter("spring-security-fail-redirect");
		if (StringUtils.hasText(failTargetUrl)) {
			saveException(request, exception);
			if (super.isUseForward()) {
				logger.debug("Forwarding to " + failTargetUrl);
				request.getRequestDispatcher(failTargetUrl).forward(request,
						response);
			} else {
				logger.debug("Redirecting to " + failTargetUrl);
				getRedirectStrategy().sendRedirect(request, response,
						failTargetUrl);
			}
		} else if (StringUtils.hasText(targetUrl) && useModalBox
				&& targetUrl.endsWith("?needLogin=true")) {
			saveException(request, exception);
			getRedirectStrategy().sendRedirect(request, response, targetUrl);
		} else {
			String loginType = (String)request.getSession().getAttribute("loginType");
			if(loginType!=null&&loginType.equals("quick")){
				String goBack = (String)request.getSession().getAttribute("goBack");
				if(goBack!=null&&!goBack.equals("")){
					if(goBack.indexOf("?")!=-1){
						goBack = goBack +"&error=true";
					}else{
						goBack = goBack +"?error=true";
					}
					setDefaultFailureUrl(goBack);
					request.getSession().setAttribute("goBack", "/");
				}else{
					setDefaultFailureUrl("/memberLoginPage?error=true");
				}
			}else if(loginType!=null&&loginType.equals("admin")){
				setDefaultFailureUrl("/loginPage?error=true");
			}else{
				setDefaultFailureUrl("/memberLoginPage?error=true");
			}
			
			super.onAuthenticationFailure(request, response, exception);
			
		}
	}

	public boolean isUseModalBox() {
		return useModalBox;
	}

	public void setUseModalBox(boolean useModalBox) {
		this.useModalBox = useModalBox;
	}

}